program fdtd
  use mod_grid

  USE DFPORT 
  use mod_workspace
  use mod_para
  use mod_migrate
  use mod_material
  use mod_upward
  use AVDef
  use DFLib



  


  implicit none
  integer::i,j,k,status
  real(8)::temp,gammafactor
  CHARACTER(80) buf

  call getarg(1,buf)
  if (len(trim(buf)) .gt. 0) then
  read(buf,*)gammafactor
  else
  gammafactor=10.0
  endif
  write(*,*)'gammafactor= ',gammafactor
 
  write(*,*) 'begain simulating'
  call timestamp()

  call mod_grid_init()
  
  call init_field()

  call material_setup()
  !delta=10D0

  dt=1E-6;gamma=gammafactor/mu*(dt/delta)**2;

   !open(99,file='chrand',form='binary')
  !read(99)(((chx(i,j,k), i=nx1-1,nx2+1), j=ny1-1,ny2+1),k=nz1-1,nz2+1)
  !read(99)(((chy(i,j,k), i=nx1-1,nx2+1), j=ny1-1,ny2+1),k=nz1-1,nz2+1)
  !read(99)(((chz(i,j,k), i=nx1-1,nx2+1), j=ny1-1,ny2+1),k=nz1-1,nz2+1)
  !close(99)
   ! do k=nz1,nz2
   !    do j=ny1,ny2
   !       do i=nx1,nx2
    !         chx(i,j,k)=rand();
     !        chy(i,j,k)=rand();
     !        chz(i,j,k)=rand();
     !     enddo
    !   enddo
  !  enddo
 allocate(arrayview(nx2-nx1+3,ny2-ny1+3)) 
 arrayview=z(:,:,nz1)
 do i=1,10
 arrayview=jac(:,:,nz1+i-1)
enddo 
 call init_ch()
 !chz(100,150,1)=1D0
 arrayview=chz(:,:,nz1)
 call faglStartWatch(arrayview, status)
 call faglShow(arrayview, status)
 call faglUpdate(arrayview, status)

 call init_upward(delta*dble(ny2-ny1+3)/dble(nx2-nx1+3),delta,z(nx1-1,ny1-1,nz1))

 call upward()

 do i=1,10000
     write(*,*) 'begin migrate step ',i
     call timestamp()
     call migrate()
     ! call upward continuation, from chz(:,:,nz1) ==> chx(:,:,nz1-1),chy(:,:,nz1-1)
     !write(*,*) 'begain upward'
     !call timestamp()
     call upward()
     write(*,*) 'begin output'
     !call timestamp()
	 !ch-->h-->ce-->e-->ch
     write(*,*)maxval(chz),maxval(abs(chz(:,:,nz1))),maxval(abs(chz(:,:,nz1+1))),maxval(abs(chz(:,:,nz1+2)))
     arrayview=chz(:,:,nz1)*sqrt(g33(:,:,nz1))
     call faglUpdate(arrayview, status)

  enddo


endprogram fdtd
